package com.zone.editor;

import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.zone.editor.inter.EditorView;
import com.zone.editor.inter.EditorViewState;
import com.zone.editor.inter.OnEditorListener;
import com.zone.editor.photoEditor.R;

public class Text extends Graphic {

    private final MultiTouchListener mMultiTouchListener;
    private final Typeface mDefaultTextTypeface;
    private final GraphicManager mGraphicManager;
    private final EditorView editorView;
    private final EditorViewState mViewState;
    private TextView mTextView;

    public Text(EditorView editorView,
                MultiTouchListener multiTouchListener,
                EditorViewState viewState,
                Typeface defaultTextTypeface,
                GraphicManager graphicManager
    ) {
        super(editorView.getContext(), graphicManager);
        this.editorView = editorView;
        mViewState = viewState;
        mMultiTouchListener = multiTouchListener;
        mDefaultTextTypeface = defaultTextTypeface;
        mGraphicManager = graphicManager;
        setupGesture();
    }

    public void buildView(String text, TextStyleBuilder styleBuilder) {
        mTextView.setText(text);
        if (styleBuilder != null)
            styleBuilder.applyStyle(mTextView);
    }

    private void setupGesture() {
        MultiTouchListener.OnGestureControl onGestureControl = buildGestureController(editorView, mViewState);
        mMultiTouchListener.setOnGestureControl(onGestureControl);
        View rootView = getRootView();
        rootView.setOnTouchListener(mMultiTouchListener);
    }


    @Override
    ViewType getViewType() {
        return ViewType.TEXT;
    }

    @Override
    int getLayoutId() {
        return R.layout.view_photo_editor_text;
    }

    @Override
    void setupView(View rootView) {
        mTextView = rootView.findViewById(R.id.tvPhotoEditorText);
        if (mTextView != null && mDefaultTextTypeface != null) {
            mTextView.setGravity(Gravity.CENTER);
            mTextView.setTypeface(mDefaultTextTypeface);
        }
    }

    @Override
    void updateView(View view) {
        String textInput = mTextView.getText().toString();
        int currentTextColor = mTextView.getCurrentTextColor();
        OnEditorListener photoEditorListener = mGraphicManager.getOnEditorListener();
        if (photoEditorListener != null) {
            photoEditorListener.onEditTextChangeListener(view, textInput, currentTextColor);
        }
    }
}
